package com.design_patterns.chain_of_responsibility.version;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-28 20:53
 **/

/**
 * 按顺序执行
 */
public class ServletMain {

    public static void main(String[] args) {
        Request request = new Request();
        request.setStr(" 干坏事 <script> location.href='www.xxxx.com' </script> 说坏话：工作 996 ");
        Response response = new Response();
        response.setStr("");

        FilterChain chain = new FilterChain();
        chain.add(new HTMLFilter()).add(new SensitiveFilter());
        chain.doFilter(request, response);
        System.out.println(request.str);

    }

    interface Filter {
        boolean doFilter(Request request, Response response);
    }

    static class HTMLFilter implements Filter {
        @Override
        public boolean doFilter(Request request, Response response) {
            request.str = request.str.replaceAll("<", "[").replaceAll(">", "]");
            return true;
        }
    }

    static class Request {
        String str;

        public void setStr(String str) {
            this.str = str;
        }
    }

    static class Response {
        String str;

        public void setStr(String str) {
            this.str = str;
        }
    }

    static class SensitiveFilter implements Filter {
        @Override
        public boolean doFilter(Request request, Response response) {
            request.str = request.str.replaceAll("996", "955");
            return true;
        }
    }

    static class FilterChain implements Filter {

        List<Filter> filters = new ArrayList<>();

        public FilterChain add(Filter f) {
            filters.add(f);
            return this;
        }

        @Override
        public boolean doFilter(Request request, Response response) {
            for (Filter f : filters) {
                f.doFilter(request, response);
            }
            return true;
        }
    }
}
